package com.example.word.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dict.R;
import com.example.word.MyApplication;
import com.example.word.adapter.CollectAdapter;
import com.example.word.adapter.WordManageAdapter;
import com.example.word.bean.Collect;
import com.example.word.bean.Dict;
import com.example.word.bean.Word;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.util.StringUtils;
import com.example.word.widget.ActionBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单词管理
 */
public class WordManageActivity extends AppCompatActivity {
    private Activity myActivity;
    private ActionBar mTitleBar;//标题栏
    private LinearLayout llEmpty;
    private RecyclerView rvCollectList;
    private WordManageAdapter wordManageAdapter;
    private List<Word> wordList;
    private String account,searchText;
    private Spinner dictSelect;
    private ImageView ivSearch;//搜索图标
    private FloatingActionButton btnAdd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_manage);
        myActivity = this;
        rvCollectList = findViewById(R.id.rv_collect_list);
        dictSelect = findViewById(R.id.dictSelect);
        ivSearch = findViewById(R.id.iv_search);
        llEmpty = findViewById(R.id.ll_empty);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(myActivity, "单词管理", R.drawable.ic_back, R.drawable.search, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
                searchClick();
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
        }
        btnAdd = (FloatingActionButton) findViewById(R.id.btn_add);
        //加号点击事件
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开新增单词页面
                Intent intent = new Intent(myActivity, AddWordActivity.class);
                startActivityForResult(intent, 100);
            }
        });
        //搜索
        ivSearch.setOnClickListener(v -> {
            loadData();//加载数据
        });
        initView();
    }

    private void initView() {
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        HttpUtils.sendGetRequest("/getDictList", new HashMap<>(), myActivity, Dict.class, response -> {
            List<Dict> dictList = response.getDataList();
            List<String> itemsArray = new ArrayList<>();
            for (Dict dict : dictList) {
                itemsArray.add(dict.getDict());
            }
            // 创建 ArrayAdapter 并设置下拉选项的样式
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, itemsArray);
            // 设置下拉列表的样式
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // 将适配器设置到 Spinner
            dictSelect.setAdapter(adapter);
            dictSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    loadData();
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    loadData();
                }
            });

            LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
            //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            //=1.3、设置recyclerView的布局管理器
            rvCollectList.setLayoutManager(layoutManager);
            //==2、实例化适配器
            //=2.1、初始化适配器
            wordManageAdapter = new WordManageAdapter(llEmpty, rvCollectList);
            //=2.3、设置recyclerView的适配器
            rvCollectList.setAdapter(wordManageAdapter);
            loadData();//加载数据
            wordManageAdapter.setItemListener(word -> {
                Intent intent = new Intent(myActivity, AddWordActivity.class);
                intent.putExtra("word", word);
                startActivityForResult(intent, 100);
            });
        });

    }

    /**
     * 加载数据
     */
    private void loadData(String... content) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("dict", dictSelect.getSelectedItem().toString());
        if (content.length > 0) {
            requestParam.put("wordLike", content[0]);
        }
        HttpUtils.sendGetRequest("/getWordList", requestParam, myActivity, Word.class, collectResponse -> {
            wordList = collectResponse.getDataList();
            if (wordList != null && wordList.size() > 0) {
                rvCollectList.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
                wordManageAdapter.addItem(wordList);
            } else {
                rvCollectList.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        });
    }

    public void searchClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.a1);//设置图标
        builder.setTitle("搜索");
        // 创建一个 EditText 控件用于输入
        final EditText inputEditText = new EditText(this);
        inputEditText.setHint("请输入搜索关键字");
        if (StringUtils.isNotEmpty(searchText)) {
            inputEditText.setText(searchText);
        }
        builder.setView(inputEditText);
        // 设置对话框的积极按钮（确定按钮）以及点击事件
        builder.setPositiveButton("确定", (dialog, which) -> {
            // 在这里处理确定按钮的点击事件，可以获取输入框中的文本
            String userInput = inputEditText.getText().toString();
            searchText = userInput;
            // 处理用户输入...
            loadData(userInput);
        });
        builder.setNegativeButton("重置", (dialog, which) -> {
            searchText = "";
            loadData();
        }
        );
        AlertDialog a = builder.create();
        a.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}